package com.example.demoofimagedownloadapp.presenter;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.demoofimagedownloadapp.bean.DataBean;
import com.example.demoofimagedownloadapp.contract.MusicWindowContract;
import com.example.demoofimagedownloadapp.model.MusicModel;
import com.example.demoofimagedownloadapp.view.MusicWindowActivity;
import com.example.demoofimagedownloadapp.view.utils.ImageAdapter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MusicWindowPresenter extends BasePresenter<MusicWindowContract.View>
        implements MusicWindowContract.Presenter {
    private static long MAX_PROGRESS = 1000;
    private static final int MIN_PROGRESS = 0;
    private static long PROGRESS_UNIT = 1000;
    private static final String ERROR_LIST_NULL = "LIST is NULL";
    private static final String ERROR_PLAYER_STATUS = "has PAUSED/PLAYED";
    private static final String TAG = MusicWindowPresenter.class.getName();
    public static final int DIRECTION_NEXT = 1;
    public static final int DIRECTION_PREVIOUS = 2;
    private static Integer FIRST_SONG_ID = null;
    private MusicWindowContract.View mView = null;
    private MusicModel mMusicModel;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private Integer mProgress = 0;
    private List<DataBean> mShowList = new ArrayList<>();
    /**
     * @value true:playing,false:paused
     */
    public boolean mPlayerFlag = false;

    public MusicWindowPresenter (Context context) throws FileNotFoundException {
        mMusicModel = new MusicModel(context);
        mMusicModel.getAllMediaList(context,null);
    }
    Thread progressListenThread  = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                synchronized (MusicWindowPresenter.class) {
                    while (mediaPlayer!=null){
                        if(mediaPlayer.isPlaying()){
                            long currentPosition = mediaPlayer.getCurrentPosition();

                            mProgress = (int)(currentPosition/PROGRESS_UNIT);
                            mView.updateProgress((int)(currentPosition/PROGRESS_UNIT));
                            Thread.sleep(500);
                        }
                        continue;
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    });
    public void initMediaPlayer() {
        try {
            if(FIRST_SONG_ID == null){
                FIRST_SONG_ID = 0;
            }
            mediaPlayer.setDataSource(mMusicModel.mMediaList.get(FIRST_SONG_ID).getSongPath());
            //指定音频文件路径
//            mediaPlayer.setLooping(true);
            //设置为循环播放
            MAX_PROGRESS = (mMusicModel.mMediaList.get(FIRST_SONG_ID).getDuration())/PROGRESS_UNIT;
            Log.d(TAG, "initMediaPlayer: MAX_PROGRESS/"+MAX_PROGRESS);
            mediaPlayer.prepare();
            //初始化播放器MediaPlayer

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ImageAdapter getImageAdapter(){
        mShowList.clear();
        int tempId = mMusicModel.getPlayingId();
        mShowList.add(mMusicModel.mMediaList.get(tempId));
        mShowList.add(mMusicModel.mMediaList.get((tempId+1)%mMusicModel.mMediaList.size()));
        if(tempId-1<0){
            mShowList.add(mMusicModel.mMediaList.get(mMusicModel.mMediaList.size()-1));
        } else {
            mShowList.add(mMusicModel.mMediaList.get(tempId-1));
        }
        for(DataBean dataBean:mShowList){
            dataBean.setAlbumArt(mMusicModel.getAlbumArt(dataBean.getAlbumId()));
        }
        ImageAdapter imageAdapter = new ImageAdapter(mShowList);
        return imageAdapter;
    }

    @Override
    public void setView(MusicWindowContract.View view) {
        mView = view;
    }

    @Override
    public void startPlayer() throws IOException {
        if (mMusicModel.mMediaList == null){
            mView.showErrorInfo(ERROR_LIST_NULL);
            return;
        }
        if(FIRST_SONG_ID == null){
            FIRST_SONG_ID = 0;
            initMediaPlayer();
            play(FIRST_SONG_ID, MIN_PROGRESS);
        } else {
          if(mProgress < MAX_PROGRESS&&mPlayerFlag == false){
              play(mMusicModel.getPlayingId(), mProgress);
          } else if(mProgress == MAX_PROGRESS){
              Log.d(TAG, "startPlayer: "+MAX_PROGRESS);
              nextSong();
          }
        }
    }
    private void play(int id, int progress){
        mPlayerFlag = true;

        mediaPlayer.seekTo((int) (progress*PROGRESS_UNIT));
        mProgress = progress;
        mediaPlayer.start();
        if(!progressListenThread.isAlive()){
            progressListenThread.start();
        }
        String name = mMusicModel.mMediaList.get(mMusicModel.getPlayingId()).getTitle();
        String singer = mMusicModel.mMediaList.get(mMusicModel.getPlayingId()).getArtist();
//        if(name!=null){
//            name = name.split("")[0];
//        }
        mView.updateMusicPlayer(
                MAX_PROGRESS,
                name+" - "+singer,
                null
        );
    }
    @Override
    public void pausePlayer() {
        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();

            mPlayerFlag = false;
            mView.updateMusicPlayer(MAX_PROGRESS, null, null);

        } else {
            mView.showErrorInfo(ERROR_PLAYER_STATUS);
            return;
        }
    }

    @Override
    public void nextSong() throws IOException {
        if (mMusicModel.mMediaList == null){
            mView.showErrorInfo(ERROR_LIST_NULL);
            return;
        }
        mediaPlayer.reset();
        Log.d(TAG, "nextSong: NOW/"+mMusicModel.getPlayingId());
        mMusicModel.setNext();
        Log.d(TAG, "nextSong: NEXT/"+mMusicModel.getPlayingId());
        mediaPlayer.setDataSource(mMusicModel.getSourcePath());
        MAX_PROGRESS = mMusicModel.mMediaList
                .get(mMusicModel.getPlayingId())
                .getDuration()/PROGRESS_UNIT;
        Log.d(TAG, "nextSong: MAX_PROGRESS/"+MAX_PROGRESS);
        mediaPlayer.prepare();
        play(mMusicModel.getPlayingId(),MIN_PROGRESS);
//        nextAlbumart();
    }

    public void nextAlbumart(){
        mShowList.remove(2);
        DataBean dataBean = mMusicModel.mMediaList.get(
                (mMusicModel.getPlayingId()+1)%mMusicModel.mMediaList.size());
        dataBean.setAlbumArt(mMusicModel.getAlbumArt(dataBean.getAlbumId()));
        mShowList.add(
                dataBean
        );
        mShowList.add(mShowList.get(0));
        mShowList.remove(0);
        mView.updateMusicAlbumart(mShowList, DIRECTION_NEXT);
    }
    public void previousAlbumart () {
        DataBean dataBean = mMusicModel.mMediaList.get(
                mMusicModel.getPlayingId()-1<0?
                        mMusicModel.mMediaList.size()-1 : mMusicModel.getPlayingId()-1
        );
        dataBean.setAlbumArt(mMusicModel.getAlbumArt(dataBean.getAlbumId()));

        List<DataBean> list = new ArrayList<>();
        for(DataBean dataBean1:mShowList){
            list.add(dataBean1);
        }
        mShowList.clear();
        mShowList.add(list.get(2));
        mShowList.add(list.get(0));
        mShowList.add(dataBean);


        mView.updateMusicAlbumart(mShowList, DIRECTION_PREVIOUS);
    }
    @Override
    public void previousSong() throws IOException {
        if (mMusicModel.mMediaList == null){
            mView.showErrorInfo(ERROR_LIST_NULL);
            return;
        }

        mediaPlayer.reset();
        Log.d(TAG, "previousSong: NOW/"+mMusicModel.getPlayingId());
        mMusicModel.setPrevious();
        Log.d(TAG, "previousSong: PRE/"+mMusicModel.getPlayingId());
        mediaPlayer.setDataSource(mMusicModel.getSourcePath());
        MAX_PROGRESS = mMusicModel.mMediaList
                .get(mMusicModel.getPlayingId())
                .getDuration()/PROGRESS_UNIT;
        mediaPlayer.prepare();
        play(mMusicModel.getPlayingId(),MIN_PROGRESS);
//        previousAlbumart();
    }

    @Override
    public void getSongList(int numInOnePage) {

    }

    @Override
    public void setProgress(int progress) {
        play(mMusicModel.getPlayingId(),progress);
    }

    @Override
    public void stop() {
        super.stop();
        try {
            progressListenThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        mMusicModel = null;
        progressListenThread = null;

    }
}
